package com.cucn.educenter.controller;


import com.cucn.commonutils.JwtUtils;
import com.cucn.commonutils.Result;
import com.cucn.commonutils.ordervo.UcenterMemberOrder;
import com.cucn.educenter.entity.RegisterVO;
import com.cucn.educenter.entity.UcenterMember;
import com.cucn.educenter.service.UcenterMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author KouChaoJie
 * @since 2021-10-10
 */
@RestController
//@CrossOrigin
@RequestMapping("/educenter/member")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService memberService;

    /**
     * 登录方法
     *
     * @param member 登录用户信息,封装了手机号和密码
     */
    @PostMapping("/login")
    public Result loginUser(@RequestBody UcenterMember member) {
        //调用service方法实现登录
        //返回token值,使用jwt生成
        String token = memberService.login(member);

        return Result.ok().data("token", token);
    }

    /**
     * 注册方法
     *
     * @param registerVO 注册的用户信息
     */
    @PostMapping("/register")
    public Result registerUser(@RequestBody RegisterVO registerVO) {
        memberService.register(registerVO);

        return Result.ok();
    }

    /**
     * 根据token获取用户信息,用于前端显示
     *
     * @param request request对象,用于传到header的token
     */
    @GetMapping("/getMemberInfo")
    public Result getMemberInfo(HttpServletRequest request) {
        //调取jwt工具类的方法,根据request对象获取头信息,返回用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        //查询数据库根据用户id获取用户信息
        UcenterMember member = memberService.getById(memberId);

        return Result.ok().data("userInfo", member);
    }

    /**
     * 根据用户id获取到用户信息
     *
     * @param id 用户id
     * @return 获取到的用于远程调用用户对象
     */
    @PostMapping("/getUserInfoOrder/{id}")
    public UcenterMemberOrder getUserInfoOrder(@PathVariable String id) {
        UcenterMember member = memberService.getById(id);
        UcenterMemberOrder memberOrder = new UcenterMemberOrder();
        BeanUtils.copyProperties(member, memberOrder);

        return memberOrder;
    }

    /**
     * 查询某一天的注册人数
     *
     * @param day 日期
     * @return 返回注册人数
     */
    @GetMapping("/countRegister/{day}")
    public Result countRegister(@PathVariable String day) {
        Integer count = memberService.countRegisterDay(day);

        return Result.ok().data("countRegister",count);
    }
}